import socket
import threading
import pymysql
import json
from datetime import datetime
import random
class NetServer():

    def __init__(self) -> None:
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(("", 8787))
        self.socket.listen(5)

        self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='W13145..', db='linetalk')
        self.cur = self.conn.cursor()

        self.clients = []
        self.clients_name_ip = {}

    def get_conn(self):
        while True:
            client, addr = self.socket.accept()
            print(addr)
            data = "与服务器连接成功，请输入用户名密码登录！"
            client.send(data.encode())
            self.clients.append(client)
            # 服务器启动多个线程处理每个客户端的消息
            t = threading.Thread(target=self.get_msg,
                                 args=(client, self.clients, self.clients_name_ip, addr))  # 创建多线程，每接受一个客户端的连接，就建立一个新的线程
            t.start()

    def get_msg(self, client, clients, clients_name_ip, addr):
        login_js = client.recv(1024).decode()
        login_json = json.loads(login_js)
        username = login_json["username"]
        password = login_json["password"]
        if self.login_Valid(username, password):
            clients_name_ip[addr] = username
            client.send("yes".encode())
        else:
            data = "用户名或密码错误！"
            client.send(data.encode())
        while True:
            try:
                recv_data = client.recv(1024).decode()
            except Exception as e:
                break
            dt = datetime.now()
            time_obj = dt.time()
            formatted_time = time_obj.strftime('%H:%M:%S')
            for c in clients:
                c.send((clients_name_ip[addr]+" "+formatted_time+"\n"+recv_data).encode())

    def login_Valid(self, username, password):
        sql = f"select * from user_acounts where username='{username}' and password ='{password}'"
        self.cur.execute(sql)
        results = self.cur.fetchall()
        if len(results) > 0:
            return True

    def key_send(self):
        requests_count = 0
        word_bank = [
            "风起云涌", "水落石出", "春暖花开", "秋高气爽",
            "天长地久", "一心一意", "二话不说", "三心二意",
            "四面楚歌", "五颜六色", "六神无主", "七嘴八舌",
            "八仙过海", "九牛一毛", "十全十美"
        ]
        sign2 = "2:"
        with self.conn:
            while True:
                try:
                    data = self.conn.recv(1024).decode('utf-8')
                    if data == "REQUEST_DATA":
                        requests_count += 1
                        if requests_count == 2:
                            chosen_word = random.choice(word_bank)
                            word = sign2+chosen_word
                            for c in self.clients:
                                c.send(word.encode('utf-8'))
                                print(f"Sending: {word}")
                                requests_count = 0
                        else:
                            break
                    elif data == "fail":
                        for c in self.clients:
                            c.send(b"1:fail")
                        requests_count = 0
                    elif data == "success":
                        for c in self.clients:
                            c.send("1:success")
                        requests_count = 0
                    else:
                        break
                except:
                    break

if __name__ == '__main__':
    server = NetServer()
    server.get_conn()
